package cn.tedu.gateway;

import cn.tedu.common.util.JWTUtil;
import cn.tedu.common.util.JwtConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class JwtFilter implements GlobalFilter , Ordered {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String uri = request.getURI().toString();
        // 记得截取 Breaer 空格
        String token = request.getHeaders().getFirst("Authorization");
        if("options".equals(request.getMethod())){
            return chain.filter(exchange);
        }
        if(uri.contains("/ry/client/login")){
            return chain.filter(exchange);
        }
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
        }

        if(token.startsWith(JwtConstants.AUTHORIZATION_BEARER)){
            token=token.substring(JwtConstants.AUTHORIZATION_BEARER.length());
        }

        // 需要远程调用 SSO 服务checkToken
        try{
            JWTUtil.verify(token);
        }catch (Exception e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String clientId =(String) JWTUtil.getUserInfo(token).get("clientId");
        // 唯一登录
        // sso:userId  token
        String redisToken = stringRedisTemplate.opsForValue().get(JwtConstants.SSO+clientId);
        redisToken=redisToken.substring(1,redisToken.length()-1);
        // 通过当前1号id   再 equels 比较 token 和用户传过来的token是否一致
        // 一致则放行，不一致则401
        if (redisToken == null || !redisToken.equals(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //刷新token
        //获取当前的时间
        long nowtime=System.currentTimeMillis();
        //获取redis里存token的时间
        Date expireDate = JWTUtil.getTokenInfo(token).getExpiresAt();
        //比对两个时间，如不一致则生成新的token
        if (expireDate.getTime() - nowtime < JwtConstants.REFRESH_TIME) {
            String newtoken = JWTUtil.getToken(JWTUtil.getUserInfo(token));
            stringRedisTemplate.opsForValue().set(JwtConstants.SSO+JWTUtil.getUserInfo(token).get("clientId"),newtoken);
            response.getHeaders().add(JwtConstants.REFRESH_TOKEN_HEADER_NAME, newtoken);
            response.getHeaders().set("Access-Control-Expose-Headers",JwtConstants.REFRESH_TOKEN_HEADER_NAME);
            //response.setStatusCode(HttpStatus.RESET_CONTENT);
            return chain.filter(exchange);
        }



        System.out.println("I`m过滤器1"+uri);

        //代表通过
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
